#include <nds.h>
#include <dswifi7.h>
#include <nds/fifocommon.h>
#include <nds/fifomessages.h>

#include "command7.h"

//---------------------------------------------------------------------------------
void myInputGetAndSend()
//---------------------------------------------------------------------------------
{
	static bool penDown = false;

	touchPosition tempPos = {0};
	FifoMessage msg = {0};
	u16 keys = REG_KEYXY;

	if(!touchPenDown())
	{
		keys |= (1<<6);
  }
	else
	{
		keys &= ~(1<<6);
	}

	msg.SystemInput.keys = keys;

	if (keys & (1<<6))
	{
		penDown = false;	
	}
	else
	{
		msg.SystemInput.keys |= (1<<6);

		if (penDown)
		{
			touchReadXY(&tempPos);	
			if (tempPos.rawx && tempPos.rawy)
			{
				msg.SystemInput.keys &= ~(1<<6);
				msg.SystemInput.touch = tempPos;
			}
			else
			{
				penDown = false;
			}
		}
		else
		{
			penDown = true;
		}
	}	

	msg.type = SYS_INPUT_MESSAGE; //set message type
	fifoSendDatamsg(FIFO_SYSTEM, sizeof(msg), (u8*)&msg);
}

//---------------------------------------------------------------------------------
int main() {
//---------------------------------------------------------------------------------
	irqInit();
	fifoInit();
	initClockIRQ();
	readUserSettings();
	SetYtrigger(80);

	installWifiFIFO();
	//installSystemFIFO();
	fifoSetDatamsgHandler(FIFO_USER_01, fifoMyDataHandler, 0);
		
	irqSet(IRQ_VCOUNT, myInputGetAndSend);
	irqSet(IRQ_VBLANK, Wifi_Update);
	irqEnable( IRQ_VBLANK | IRQ_VCOUNT | IRQ_NETWORK );
	
	REG_SOUNDCNT = SOUND_VOL(127) | SOUND_ENABLE;

	while (1) swiWaitForVBlank();
	return 0;
}
